<template>
	<view class="pickup">

		<view class="list">

			<view class="pick-item" @tap="checkPickup(item)" v-for="item,index in pickup_list">

				<view class="name">
					{{item.name}}
				</view>

				<view class="address">
					{{item.province}}
					{{item.city}}
					{{item.area}}
					{{item.street}}
					{{item.detail}}
				</view>

				<view class="distance" v-show="item.distance">
					距离：{{ item.distance }}
				</view>
				<view class="edit"></view>

			</view>

		</view>

	</view>
</template>

<script>
	const appInstance = getApp();
	export default {
		data() {
			return {
				pickup_list: [],
				latLng: {
					lat: '',
					lng: ''
				}
			}
		},
		onLoad: function(options) {

			this.init();

		},
		onPullDownRefresh: function() {

			var p = new Promise(this.init);
			p.then(function(result) {
				uni.stopPullDownRefresh();
			});
		},
		methods: {
			init: function(resolve) {

				var t = this;

				// this.getLocation(); // 获取距离的方法 暂时注释掉，插件安装成功后打开

				var url = '&r=pickup.get_list';

				appInstance.globalData.request(url, {}, 'GET', function(res) {

					t.pickup_list = res.data
					
					// t.getLocation();   // 获取距离的方法 暂时注释掉，插件安装成功后打开

					if (typeof resolve == 'function') {
						resolve(res.data);
					}

				});

			},



			getLocation: function(callback) {

				var t = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						t.latLng = {
							lat: res.latitude,
							lng: res.longitude
						};
						t.getPickupDistance();

					}
				});
			},

			getPickupDistance: function() {

				var t = this;
				this.pickup_list.forEach(function(item) {

					item.distance = t.getDistance(item.latitude, item.longitude, t.latLng.lat, t.latLng.lng);

					if (item.distance > 1000) {
						item.distance /= 1000;
						item.distance = item.distance.toFixed(2);
						item.distance += 'km';
					} else {
						item.distance = parseInt(item.distance);
						item.distance += 'm';
					}
					// console.log(item.distance);
				});


			},

			toRad: function(d) {
				return d * Math.PI / 180;
			},

			getDistance: function(lat1, lng1, lat2, lng2) {

				var dis = 0;

				var radLat1 = this.toRad(lat1);
				var radLat2 = this.toRad(lat2);
				var deltaLat = radLat1 - radLat2;
				var deltaLng = this.toRad(lng1) - this.toRad(lng2);
				var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) *
					Math.pow(Math.sin(deltaLng / 2), 2)));
				return dis * 6378137;

			},

			checkPickup: function(pickup) {

				// var pickup = e.currentTarget.dataset.item;

				uni.setStorageSync('pickup', pickup);
				uni.navigateBack();

			},
		}
	}
</script>

<style lang="less">
	@import './list.less';
</style>
